package com.comprosoft.telnet.command;

import com.comprosoft.telnet.Constants;
import com.comprosoft.telnet.Encoding;
import com.comprosoft.telnet.command.Command;
import com.comprosoft.telnet.command.CommandResult;
import com.comprosoft.telnet.configuration.ServerProperties;
import com.comprosoft.telnet.io.IOHandler;
import com.sun.deploy.util.StringUtils;
import org.apache.commons.lang.StringEscapeUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;

/**
 * Command used to exit the Telnet server
 */
public class SystemCommandHandler extends Command {
    private static final Logger logger = Logger.getLogger("SystemCommandHandler");


    public SystemCommandHandler(IOHandler io) {
        super(io, "sys");
    }

    public String getOsCmd() {
        Properties props = System.getProperties(); //获得系统属性集
        String osName = props.getProperty("os.name"); //操作系统名称
        if (osName.toLowerCase().contains("linux")) {
            return "/bin/sh -c ";
        } else if (osName.toLowerCase().contains("windows")) {
            return "cmd /c ";
        } else {
            throw new RuntimeException("服务器不是linux|windows操作系统");
        }
    }

    @Override
    public CommandResult handleCommand(String args[]) {
        StringBuffer commandStr = new StringBuffer();
        int i = 0;
        for (String arg : args) {
            if (i != 0) {
                commandStr.append(arg).append(" ");

            }
            i++;
        }
        logger.log(Level.INFO, "sys execute:" + commandStr.toString());
        boolean ifError = false;

//        super.getIOHandler().WriteLine("sys execute:" + commandStr.toString());
        try {
            String jarPath = Matcher.quoteReplacement(ServerProperties.JAR_PATH.getValue());
            String command = StringEscapeUtils.unescapeHtml(commandStr.toString());
            ProcessBuilder pb = new ProcessBuilder((getOsCmd() +
                    command).split(" "));
//            pb.redirectErrorStream(true);
            Process process = null;
            BufferedReader br = null;
            BufferedReader brError = null;
            try {
                process = pb.start();
                br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    super.getIOHandler().WriteLine(line);
                    System.out.println(line);
                }

                brError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GBK"));
                String lineError = null;
                while ((lineError = brError.readLine()) != null) {
                    super.getIOHandler().WriteLine(lineError);
                    System.out.println(lineError);
                    ifError = true;
                }

                process.waitFor();
            } finally {
                if (br != null) {
                    br.close();
                }
                if (process != null) {
                    process.exitValue();
                    process.destroy();
                    Runtime.getRuntime().gc();
                }
            }
            if (ifError) {
                return com.comprosoft.telnet.command.CommandResult.COMMAND_EXIT;
            } else {
                return com.comprosoft.telnet.command.CommandResult.COMMAND_OK;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommandResult.COMMAND_EXIT;

        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 20; i++) {
            String subCommond = null;
            if (i % 2 == 0) {
                subCommond = "start";
            } else {
                subCommond = "stop";

            }
            ProcessBuilder pb = new ProcessBuilder(("cmd /c " +
                    "net " + subCommond + " telcat").split(" "));
            pb.redirectErrorStream(true);
            Process process = null;
            BufferedReader br = null;
            try {
                process = pb.start();
                br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
                process.waitFor();
            } finally {
                if (br != null) {
                    br.close();
                }
                if (process != null) {
                    process.exitValue();
                    process.destroy();
                    Runtime.getRuntime().gc();
                }
            }

        }
    }

}

